package com.caesar.exer2;

/**
 * @author caesar
 * @date 2025/7/21
 * @Description:
 * @apiNote
 */
public class Racer extends Thread{      //跑步比赛的运动员类
    private static long distance;      	//全程距离，单位米
    private String name;        		//运动员名字
    private long runTime;       		//每米需要时间，单位毫秒
    private long restTime;      		//每10米的休息时间，单位毫秒
    private long time;          		//跑完全程的总时间
    private static boolean runFlag = true;	//用于标记是否继续跑，即结束线程的标记
    private boolean finished;

    public Racer(String name, long runTime, long restTime) {
        super();
        this.name = name;
        this.runTime = runTime;
        this.restTime = restTime;
    }

    @Override
    public void run() {
        long sum = 0;
        long start = System.currentTimeMillis();
        while (sum < distance && runFlag) {
            try {
                Thread.sleep(runTime);// 每米距离，该运动员需要的时间
                sum++;
                System.out.println(name + "已经跑了" + sum + "米，继续努力奔跑...");

                if (sum % 10 == 0 && sum < distance && runFlag) {
                    // 每10米休息一下
                    System.out.println(name + "已经跑了" + sum + "米，开始休息....");
                    Thread.sleep(restTime);
                }

            } catch (InterruptedException e) {
                System.out.println(name  + "未跑完就结束比赛");
            }
        }
        runFlag = false;
        if(sum >= distance) {
            finished = true;
        }
        long end = System.currentTimeMillis();
        time = end - start;
        System.out.println(name + "跑了" + sum + "米，共用时" + (double)time / 1000.0 + "秒");
    }

    public long getTime() {
        return time;
    }
    public boolean isFinished() {
        return finished;
    }

    public static void setDistance(long distance) {
        Racer.distance = distance;
    }

    public static boolean isRunFlag() {
        return runFlag;
    }
}

